﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Excel = Microsoft.Office.Interop.Excel;
using System.IO;

namespace ExchangeCurrencyRate.Parser
{
    class Program
    {
        static void Main(string[] args)
        {
            var result = BloombergParser.Parse();
            using (StreamWriter writer = File.CreateText(Path.Combine(AppDomain.CurrentDomain.RelativeSearchPath ?? AppDomain.CurrentDomain.BaseDirectory, string.Format("Currency.Rates.{0:yyyyMMdd}.csv", DateTime.Now))))
            {
                foreach (string k in result.Keys.OrderBy(x => x))
                {
                    writer.WriteLine("{1}{0}{2}", System.Globalization.CultureInfo.InvariantCulture.TextInfo.ListSeparator, k, result[k]);
                }
            }
            Excel.Application app = new Excel.ApplicationClass();
            try
            {
                Excel.Workbook book = app.Workbooks.Add(System.Reflection.Missing.Value);
                Excel.Worksheet sheet = (Excel.Worksheet)book.Worksheets.Add(
                    System.Reflection.Missing.Value,
                    System.Reflection.Missing.Value, 1, Excel.XlSheetType.xlWorksheet);
                int iRow = 1;
                foreach (string cFrom in result.Keys.OrderBy(x => x))
                {
                    sheet.Cells[iRow + 1, 1] = cFrom;
                    int iCol = 1;
                    foreach (string cTo in result.Keys.OrderBy(x => x))
                    {
                        sheet.Cells[1, iCol + 1] = cTo;
                        sheet.Cells[iRow + 1, iCol + 1] = result[cTo] / result[cFrom];
                        iCol++;
                    }
                    iRow++;
                }
                book.SaveAs(
                    Path.Combine(AppDomain.CurrentDomain.RelativeSearchPath ?? AppDomain.CurrentDomain.BaseDirectory, string.Format("Currency.CrossTable.{0:yyyyMMdd}.xls", DateTime.Now)),
                    Excel.XlFileFormat.xlWorkbookNormal, System.Reflection.Missing.Value, System.Reflection.Missing.Value,
                    false, false, Excel.XlSaveAsAccessMode.xlNoChange,
                    System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value);
                book.Close(false, System.Reflection.Missing.Value, null);
            }
            finally
            {
            }
        }
    }
}
